package com.mgq.juc.threadLocal;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author MaGuangQi
 * ThreadLocal 学习
 * @date 2022-03-14 15:10
 **/
public class TestThreadLocal {
    private static ThreadLocal<String> t1 = new ThreadLocal<>();
    public static void main(String[] args) {
     t1.set("a");

       /* for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                Connection connection = Until.getConnection();
                System.out.println(connection);
            }).start();
        }*/
        System.out.println(t1.get());
    }


    static class Until {
        private static final ThreadLocal<Connection> t1 = new ThreadLocal<>();

        public static Connection getConnection() {
            Connection connection = t1.get();
            if (connection == null) {
                //创建connection对象
                connection = innerGetConnection();
                t1.set(connection);
            }
            return connection;
        }

        private static Connection innerGetConnection() {
            try {
                return DriverManager.getConnection("jdbc:mysql://localhost:3306", "root", "root");
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
